import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:lamp_app/domain/util/token_interceptors.dart';

// import 'package:flutter_duominuo/domain/util/token_interceptors.dart';
// import 'package:flutter_duominuo/util/dialog_utils.dart';
// import 'package:flutter_duominuo/util/toast_utils.dart';
import '../../utils/toast_utils.dart';
import 'network_code.dart';

import 'dart:developer';

import 'http_url.dart';
import 'network_code.dart';
import 'resource.dart';
import 'response_interceptors.dart';

///网络请求工具类,使用方法[HttpManager.getInstance().post()]
class HttpManager {
  static HttpManager? _instance;

  late Dio _dio; // 使用默认配置

  factory HttpManager() => getInstance();

  static HttpManager getInstance() {
    _instance ??= HttpManager._internal();
    return _instance!;
  }

  HttpManager._internal() {
    _dio = Dio();
    _dio.options.baseUrl = HttpUrl.baseUrl;
    _dio.options.connectTimeout = const Duration(seconds: 20);
    _dio.options.receiveTimeout = const Duration(seconds: 20);

    //打印log配置
    _dio.interceptors.add(
      LogInterceptor(
        requestBody: true,
        responseHeader: false,
        responseBody: true,
        logPrint: (obj) {
          //android会出现打印日志不全的情况
          if (kDebugMode) {
            log(obj.toString());
          }
        },
      ),
    );

    //统一处理返回结果,请求到数据后会走到ResponseInterceptors类的回调里
    _dio.interceptors.add(TokenInterceptors());
    _dio.interceptors.add(ResponseInterceptors());
  }

  ///发起网络请求
  ///[ path] 请求url
  ///[ flatMap] 请求参数
  ///[noTips] 是否需要显示错误信息的toast
  Future<Resource> get(String path,
      {Map<String, dynamic>? data, headers, noTips = false}) async {
    print('data333====>$data');
    return _netFetch(path, data, headers: headers, noTip: noTips);
  }

  ///表单形式
  Future<Resource> post(
      {String path = '', dynamic data, headers, noTips = false}) async {
    print('post_data1===>$data');
    print('post_data===>$data');
    return _netFetch(path, data,
        headers: headers, noTip: noTips, method: 'POST');
  }

  Future<Resource> put(String path, dynamic data,
      {headers, noTips = false}) async {
    return _netFetch(path, data,
        headers: headers, noTip: noTips, method: 'PUT');
  }

  Future<Resource> _netFetch(url, params,
      {String method = 'GET', headers, noTip}) async {
    print('_netFetch——data===>$params');
    Options options = Options(method: method);
    if (headers != null) {
      options.headers = headers;
    }
    resultError(DioException e) {
      // print('DioExceptionDioException-------->${e.response!.data}');
      int statusCode = NetworkCode.networkError;
      if (e.type == DioExceptionType.connectionTimeout ||
          e.type == DioExceptionType.receiveTimeout) {
        statusCode = NetworkCode.networkTimeout;
      }
      if (!noTip) {
        // eventBus.fire(HttpErrorEvent(errorResponse.statusCode, e.message));
      }
      // DialogUtils.showAlert(title: _msg);
      return Resource.error(statusCode, e.message ?? "");
    }

    Response response;
    try {
      print('method22===>${method.toUpperCase()}');
      if (method.toUpperCase() == 'GET') {
        print('params111===>$params');
        response =
            await _dio.request(url, queryParameters: params, options: options);
        print('response11===>$response');
      } else {
        response = await _dio.request(url, data: params, options: options);
        print('response22===>$response');
      }
    } on DioException catch (e) {
      print('error-------->$e');
      return resultError(e);
    }

    if (response.data is DioException) {
      return resultError(response.data);
    }
    Resource result = response.data;
    print('resultresult====>${result}');
    print('msgmsgmsg====>${result.message}');
    if (result.status == Status.error && !noTip) {
      ToastUtils.show(result.message);
      // eventBus.fire(HttpErrorEvent(200, result.message));
    }
    return result;
  }
}
